package com.atguigu.srb.core.controller.admin;


import com.alibaba.excel.EasyExcel;
import com.atguigu.common.exception.BusinessException;
import com.atguigu.common.result.R;
import com.atguigu.common.result.ResponseEnum;
import com.atguigu.srb.core.pojo.dto.ExcelDictDTO;
import com.atguigu.srb.core.pojo.entity.Dict;
import com.atguigu.srb.core.service.DictService;
import com.atguigu.srb.core.service.impl.DictServiceImpl;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.List;

/**
 * <p>
 * 数据字典 前端控制器
 * </p>
 *
 * @author Luckyh
 * @since 2022-01-25
 */
@Api(tags ="数据字典管理")
@Slf4j
@CrossOrigin
@RestController
@RequestMapping("/admin/core/dict")
public class AdminDictController {

    @Resource
    private DictServiceImpl dictServiceImpl;

    @Resource
    private DictService dictService;

    @ApiOperation(value ="Excel的批量导入")
    @PostMapping("/import")
    public R batchImport(@ApiParam(value ="Excel数据文件",required = true) @RequestParam("file") MultipartFile file){
        try {
            InputStream inputStream = file.getInputStream();
            dictServiceImpl.importData(inputStream);
            return R.ok().message("数据字典批量上传成功！");
        } catch (IOException e) {
           throw new BusinessException(ResponseEnum.UPLOAD_ERROR,e);
        }
    }

    /**
     * 文件下载（失败了会返回一个有部分数据的Excel）
     * <p>
     * 1. 创建excel对应的实体对象 参照
     * <p>
     * 2. 设置返回的 参数
     * <p>
     * 3. 直接写，这里注意，finish的时候会自动关闭OutputStream,当然你外面再关闭流问题不大
     */
    @ApiOperation(value = "Excel数据文件导出")
    @GetMapping("/export")
    public void export(HttpServletResponse response) throws IOException {
        // 这里注意 有同学反应使用swagger 会导致各种问题，请直接用浏览器或者用postman
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = URLEncoder.encode("数据字典", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        EasyExcel.write(response.getOutputStream(), ExcelDictDTO.class).sheet("数据字典").doWrite(dictServiceImpl.listDictData());
    }

    @ApiOperation(value = "根据父节点获取子节点的数据列表")
    @GetMapping("/listByparentId/{parentId}")
    public R getByParentId(
            @ApiParam(value ="父节点id",required = true)
            @PathVariable Long parentId){

            List<Dict> dictList =  dictServiceImpl.listByParentId(parentId);
            return R.ok().data("list", dictList);
    }

}

